<?php

namespace pmvc\log;

use DateTime;

class DefaultAppender
	implements Appender {

	private $fileName;
	private $formatter;
	private $fileHandle;

	/**
	 * Creates an appender that appends to the given file
	 * using the given {@link Formatter} to format the
	 * log messages.
	 * 
	 * @param string $fileName
	 * @param Formatter $formatter
	 */
	public function __construct($fileName=null, Formatter $formatter=null) {
		if ($fileName==null) {
			$fileName = realpath(sys_get_temp_dir()).DIRECTORY_SEPARATOR."pmvc.log";
		}
		if ($formatter==null) {
			$formatter = new DefaultFormatter();
		}
		$this->fileName 	= $fileName;
		$this->formatter	= $formatter;
	}

	public function __destruct() {
		$this->closeFile();
	}

	public static function newInstance($fileName, $format=DefaultFormatter::BASIC_LOG_FORMAT) {
		$formatter = ($format instanceof Formatter)
			? $format : new DefaultFormatter($format);
		return new DefaultAppender($fileName, $formatter);
	}

	private function openFile() {
		if (!isset($this->fileHandle)) {
			$this->fileHandle = fopen($this->fileName, "a+");
		}
		return $this->fileHandle;
	}

	private function closeFile() {
		if (!isset($this->fileHandle)) {
			return;
		}
		fflush($this->fileHandle);
		fclose($this->fileHandle);
		$this->fileHandle = null;
	}

	/**
	 * {@inheritDoc}
	 */
	public function append($level, DateTime $time, $name, $message) {
	    fwrite($this->openFile(), $this->formatter->format($level, $time, $name, $message));
	}

}

?>